package com.wtf.config;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.rpc.common.Serializer;

import java.util.List;

/**
 * desc: 自定义解码器
 *
 * @author tengfei wang
 * @version 1.0
 * @date Created in 11/10/2020
 */
public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;

    private Serializer serializer;


    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int len = byteBuf.readableBytes();
        if (len < 1) { return;}
        byte[] bytes = new byte[len];
        byteBuf.getBytes(0, bytes);
        String requestParameterStr = new String(bytes);
        String rpcRequestStr = requestParameterStr.substring(requestParameterStr.indexOf("{"));
        Object object = serializer.deserialize(clazz, rpcRequestStr.getBytes());
        list.add(object);

        byteBuf.skipBytes(byteBuf.readableBytes());
    }
}
